package com.construction.api.config;

import cn.hutool.json.JSONObject;
import com.construction.api.config.annotation.IgnoreResponse;
import com.construction.api.domain.model.result.BaseResult;
import com.construction.api.domain.model.result.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author dybin
 * @Date: 2021/7/1 23:03
 */
@Slf4j
@ControllerAdvice
public class GlobalResponseHandler<T> implements ResponseBodyAdvice<T> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !returnType.hasMethodAnnotation(IgnoreResponse.class) || !(returnType.getMethodAnnotation(IgnoreResponse.class).ignore());
    }

    @Override
    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if ( body instanceof BaseResult) {
            return body;
        } else if(body instanceof String || returnType.getNestedGenericParameterType().equals(String.class)){
            return (T) new JSONObject(DataResult.success(body)).toString();
        } else {
            return (T) DataResult.success(body);
        }
    }

}
